package com.raos.websocket2.interceptor;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * WebSocketInterceptor
 *  WebSocket 拦截器
 *
 * @author raos
 * @email 991207823@qq.com
 * @date 2021/10/16 9:34
 */
public class WebSocketInterceptor implements HandshakeInterceptor {

    /** 在握手之前执行该方法, 继续握手返回true, 中断握手返回false. 通过attributes参数设置WebSocketSession的属性*/
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler handler,
                                   Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            String ID = request.getURI().toString().split("ID=")[1];
            System.out.println("当前请求会话的用户ID=" + ID);
            attributes.put("WEBSOCKET_USERID", ID);
        }
        return true;
    }

    /** 完成握手之后执行该方法*/
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler handler, Exception e) {
        System.out.println("进来 webSocket 的 afterHandshake 拦截器...");
    }

}
